package com.brian.singleton.singleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-05-30 22
 **/
public enum Singleton枚举单例8 {
    SINGLETON_枚举单例;

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        System.out.println("----getName----: " +name);
        return name;
    }

    public static void main(String[] args) throws Exception {
        Singleton枚举单例8 枚举单例1 = Singleton枚举单例8.SINGLETON_枚举单例;
        Singleton枚举单例8 枚举单例2 = Singleton枚举单例8.SINGLETON_枚举单例;
        枚举单例1.setName("kawa");
        枚举单例2.getName();
        System.out.println(枚举单例1 == 枚举单例2);


        //序列化破解发现获取的是同一个对象
        //序列化
        Singleton枚举单例8 枚举单例4 = Singleton枚举单例8.SINGLETON_枚举单例;
        FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir")+"\\Singleton2.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(枚举单例4);
        oos.flush();
        oos.close();

        //反序列化
        FileInputStream fis = new FileInputStream(System.getProperty("user.dir")+"\\Singleton2.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Singleton枚举单例8 枚举单例5 = (Singleton枚举单例8) ois.readObject();
        System.out.println(枚举单例4==枚举单例5);



        //反射机制破解 会直接抛出异常 NoSuchMethodException
        Constructor<Singleton枚举单例8> constructor = Singleton枚举单例8.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Singleton枚举单例8 枚举单例3 = constructor.newInstance();
        System.out.println(枚举单例3 == 枚举单例2);


    }
}
